package com.metacube.questionbank.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.metacube.questionbank.dto.AnswerDTO;
import com.metacube.questionbank.dto.QuestionDTO;
import com.metacube.questionbank.service.Utility;
import com.metacube.questionbank.service.Validator;

@Controller
@RequestMapping("/answer")
public class PostAnswerController {
	
	@Autowired
	Validator validate;
	
	@Autowired
	Utility utility;

	
	@RequestMapping(value = "/postAnswer",  method = RequestMethod.POST)
	public ModelAndView postAnswer(@ModelAttribute AnswerDTO aDTO, @RequestParam("qId") int qId, HttpSession session,HttpServletRequest req) {
		
		QuestionDTO qDTO = new QuestionDTO();
		System.out.println(req.getServletPath());
		
		int id = (int) session.getAttribute("sessionId");
		
		int userId = id;	
			
		if(validate.checkAnswer(aDTO)) {
			
			return new ModelAndView("postAnswer.jsp","errorMessage", "Answer Body Can't be empty");
			
		} else {
			
			if (utility.initAnswer(aDTO, qId, userId)) {
				
				
				ModelAndView model = new ModelAndView("/postAnswer.jsp");
				
				return model;
				
			} else {
				
				return new ModelAndView("postAnswer.jsp","errorMessage","Your answer not valid");		
			}
			
		}
			
	}


}
